package com.epalmpay.service.agent.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.epalmpay.dto.agent.*;
import com.epalmpay.dto.member.MemberInDTO;
import com.epalmpay.dto.merchantmanage.GroupOutDTO;
import com.epalmpay.payplat.*;
import com.epalmpay.status.Rescode;
import com.epalmpay.entity.*;
import com.epalmpay.entity.profit.ProfitAgentMonth;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.usercenter.UserAuthApi;
import com.epalmpay.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.dto.activity.AgentRateInDTO;
import com.epalmpay.dto.activity.AgentRateOutDTO;
import com.epalmpay.dto.member.BalanceInDTO;
import com.epalmpay.dto.member.MemberOutDTO;
import com.epalmpay.dto.prepurchase.PrePurAgentInDTO;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.dto.system.PageDTO;
import com.epalmpay.enumdef.BizEnum.AgentStatus;
import com.epalmpay.enumdef.BizEnum.UserStatus;
import com.epalmpay.enumdef.BizEnum.WithdrawBankList;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.enumdef.ProfitEnum;
import com.epalmpay.enumdef.CommonEnum.UserType;
import com.epalmpay.mapper.AgentLevelNameMapper;
import com.epalmpay.mapper.AgentMapper;
import com.epalmpay.mapper.AgentRateMapper;
import com.epalmpay.mapper.GroupConfigMapper;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.PrePurchaseMoneyChangeMapper;
import com.epalmpay.mapper.StatisAgentMapper;
import com.epalmpay.mapper.StatisAgentMonthMapper;
import com.epalmpay.mapper.SysMessageBaseMapper;
import com.epalmpay.mapper.SysMessageInfoMapper;
import com.epalmpay.mapper.TradeOfflineMapper;
import com.epalmpay.mapper.UserbaseMapper;
import com.epalmpay.mapper.YsShopCarMapper;
import com.epalmpay.payplat.result.PayBalanceResult;
import com.epalmpay.payplat.result.PayCardCodeResult;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.service.agent.IAgentService;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;

@Service("agentService")
public class AgentServiceImpl implements IAgentService {

	@Resource
	private AgentMapper agentMapper;
	@Resource
	private AgentLevelNameMapper agentLevelNameMapper;
	@Resource
	private GroupConfigMapper groupConfigMapper;
	@Resource
	private UserbaseMapper userbaseMapper;
	@Resource
	private GroupMapper groupMapper;
	@Resource
	private AgentRateMapper agentRateMapper;
	@Resource
	private StatisAgentMonthMapper statisAgentMonthMapper;
	@Resource
	private StatisAgentMapper statisAgentMapper;
	@Resource
	private SysMessageBaseMapper sysMessageBaseMapper;
	
	@Resource
	private SysMessageInfoMapper sysMessageInfoMapper;
	@Autowired
	@Lazy
	private ITemplateMailSendService templateMailSendService;
	@Resource
	private PrePurchaseMoneyChangeMapper prePurchaseMoneyChangeMapper;
	//@Resource
	//private ProfitAgentMonthMapper profitAgentMonthMapper;
	
	@Resource
	private IWalletService walletService;
	
	@Resource
	private  YsShopCarMapper ysShopCarMapper;

	@Resource
	private TradeOfflineMapper tradeOfflineMapper;

    protected Logger logger = Logger.getLogger(this.getClass());

    @Override
	public AgentListOutDTO agentList(AgentInDTO agentInDTO, PageDTO pageDTO) throws ApplicationException {
		AgentListOutDTO agentListOutDTO = new AgentListOutDTO();
		Long groupId = agentInDTO.getGroupId(); 
		Page page = Tools.pageEmtity(pageDTO);
		agentInDTO.setPage(page);
	   if(agentInDTO.getUserType()!=null&&CommonEnum.UserType.Agents.getType()==agentInDTO.getUserType()){
		   Agent agent=agentMapper.selectByPrimaryKey(agentInDTO.getId());
	       agentInDTO.setAgentCode(agent.getMerchantCode());
	       agentListOutDTO.setAgentLevel(agent.getAgentLevel());
	    }
	   //代理商 不查询自己列表
		ArrayList<AgentInfoOutDTO> agentInfoOutDTO = agentMapper.findAgentlistPage(agentInDTO);
		GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(groupId);
		if(groupConfig==null){
			throw new ApplicationException(Rescode.FAIL,"暂未设置分润类型");
		}
		if(groupConfig.getAgentMode()==null){
			throw new ApplicationException(Rescode.FAIL,"代理商模式为空或未设置");
		}
		agentListOutDTO.setGroupAgentMode(Integer.valueOf(groupConfig.getAgentMode()));
		agentListOutDTO.setAgentOutDTOList(agentInfoOutDTO);
		agentListOutDTO.setPage(page);
		return agentListOutDTO;
	}
	
	
	@Override
	public AgentListOutDTO groupAgentlist(AgentInDTO agentInDTO, PageDTO pageDTO) throws ApplicationException {
		AgentListOutDTO agentListOutDTO = new AgentListOutDTO();
		Page page = Tools.pageEmtity(pageDTO);
		agentInDTO.setPage(page);
		ArrayList<AgentInfoOutDTO> agentInfoOutDTO = agentMapper.findGroupAgentlistPage(agentInDTO);
		agentListOutDTO.setAgentOutDTOList(agentInfoOutDTO);
		agentListOutDTO.setPage(page);
		return agentListOutDTO;
	}
	

	@Override
	public AgentInfoOutDTO findAgentView(Agent agent) throws ApplicationException {
		AgentInfoOutDTO agentInfoOutDTO =agentMapper.findAgentbaseInfo(agent);
		GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(agentInfoOutDTO.getGroupId());
		if(groupConfig==null){
			throw new ApplicationException(Rescode.FAIL,"暂未设置分润类型");
		}
		if(groupConfig.getAgentMode()==null){
			throw new ApplicationException(Rescode.FAIL,"代理商模式为空或未设置");
		}
		agentInfoOutDTO.setBankName(Tools.isEmpty(agentInfoOutDTO.getRecieveBank())?"--":BizEnum.WithdrawBankList.fromType(agentInfoOutDTO.getRecieveBank()).getName());
		return agentInfoOutDTO;
	}

	@Override
//	@Transactional
	public Boolean addAgentInfo(AgentInfoInDTO agentInfoInDTO,String url) throws ApplicationException {
		Group group = groupMapper.selectByPrimaryKey(agentInfoInDTO.getGroupId());
		String GroupId = group.getPayGroupCode();
		String CustomerName = agentInfoInDTO.getRecieveName();//姓名  recieveName
		
		
		String MobilePhone = agentInfoInDTO.getPrincipalMobile();
		String OrgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		// 生成UserBase
		String PayPwd = agentInfoInDTO.getPassword();  
		Userbase userbase = new Userbase();
		userbase.setGmtCreate(new Date());
		userbase.setGmtModified(new Date());
		userbase.setUsername(agentInfoInDTO.getUsername());
		userbase.setPassword(new SimpleHash("SHA-1", agentInfoInDTO.getUsername(), PayPwd).toString());
		userbase.setUserType(UserType.Agents.getType());
		userbase.setStatus(UserStatus.Stop.getType());
		userbase.setGroupId(group.getId());
		userbase.setRoleId("1"); 
		userbaseMapper.insertKey(userbase);
		Agent agent  = new Agent();
		try {
			PropertyCopyUtil.copyPropertiesExclude(agentInfoInDTO, agent,"agentId");
		} catch (Exception e) {
			e.printStackTrace();
			throw new ApplicationException(Rescode.FAIL,"对象复制异常");
		}
		agent.setUserId(userbase.getId());
		agent.setGmtCreate(new Date());
		agent.setCreator(agentInfoInDTO.getLastUpdator());
		agent.setPacketStatus(true);
		agent.setPayPassword(PayPwd);
		agent.setGroupId(group.getId());
		/*** 当前添加的用角色为渠道或者渠道的管理员**/
		agent.setPrePurchaseMoney(0);
		String UserId = GroupId + UtilFun.formatNumber(agent.getUserId(), 10);
		String PwdAnswer = "000000";
		String PwdQuest = "000000";
		String Email = agentInfoInDTO.getUsername();
		String priOrpub = agent.getRecieveAccountType() == 1 ? "22" : "11";
		    //所属代理商下拉框不为空
			if (agentInfoInDTO.getParentId() != null) {
				Agent parentAgent = agentMapper.selectByPrimaryKey(agentInfoInDTO.getParentId());
				if (parentAgent == null) {
					throw new ApplicationException(Rescode.FAIL,"上级代理商不存在");
				}
				agent.setAgentLevel(parentAgent.getAgentLevel() + 1);
				String parentCode = parentAgent.getMerchantCode();
				//同一级+5
				String merchantCode = agentMapper.selectMaxMerchantCode(parentCode, parentCode.length() + 5);
				if (StringUtils.isBlank(merchantCode)) {
					//同级不存在
					agent.setMerchantCode(parentCode+"00001");
				} else {
					int merCode = Integer.parseInt(merchantCode.substring(merchantCode.length() - 5), 10);
					String merchantCode_ = String.format("%05d", merCode+1);
					agent.setMerchantCode(parentCode + merchantCode_);
				}
			} else {
				//代理商发展
				if(CommonEnum.UserType.Agents.getType()==agentInfoInDTO.getUserType()){
					//查询父级详情------
					      Agent agentInfo=null;
					     if(agentInfoInDTO.getParentId()==null){
					    	  agentInfo=agentMapper.selectByPrimaryKey(agentInfoInDTO.getAgentId());
					     }else{
					    	  agentInfo=agentMapper.selectByPrimaryKey(agentInfoInDTO.getId());
					     }
						   agent.setAgentLevel(agentInfo.getAgentLevel() + 1);
						   agent.setParentId(agentInfo.getId());
						  //同一级+5
						   String merchantCode = agentMapper.selectMaxMerchantCode(agentInfo.getMerchantCode(), agentInfo.getMerchantCode().length() + 5);
						  if (StringUtils.isBlank(merchantCode)) {
								//同级不存在
								agent.setMerchantCode(agentInfo.getMerchantCode()+"00001");
								agent.setId(null); 
							} else {
								int merCode = Integer.parseInt(merchantCode.substring(merchantCode.length() - 5), 10);
								String merchantCode_ = String.format("%05d", merCode+1);
								agent.setMerchantCode(agentInfo.getMerchantCode() + merchantCode_);
								agent.setId(null); 
							}
				}else{
						//大商户创建
						agent.setAgentLevel(1);
						agent.setParentId(null);
						String merchantCode = agentMapper.selectMaxMerchantCode(null, 5);
						if (StringUtils.isBlank(merchantCode)) {
							//为空 从00001开始计算
							agent.setMerchantCode("00001");
						} else {
							int merCode = Integer.parseInt(merchantCode, 10);
							String merchantCode_ = String.format("%05d", merCode+1);  
							agent.setMerchantCode(merchantCode_);
						}
				}
			}
			String SysTraceNum = UtilFun.createRandomNum(10);
			String OrgOrderNum = DateUtils.getDateTimeString("yyyyMMddHHmmsss", new Date())+UtilFun.createRandomNum(5);
			String CardNum = agentInfoInDTO.getRecieveAccountNo();
			String issuerId = WithdrawBankList.fromType(agentInfoInDTO.getRecieveBank()).getName();
			agent.setAgentStatus(Byte.valueOf(AgentStatus.Stop.getType()+""));
			agent.setSource(BizEnum.AgentSource.Inside.getType());
			agent.setPacketStatus(true);
			agent.setPacketNum(UserId);
			if(agentInfoInDTO.getSort()!=null){
				agent.setSort(agentInfoInDTO.getSort());
			}else{
				agent.setSort(0);
			}
			
			agent.setPrePurchaseStatus(0);
			agent.setRecommendUrl(null);
			agent.setRecommendLink(null);

			//身份证
			String CertNo =null;
			String cardIntegral = "000000000000";
			if (StringUtils.isNotBlank(agentInfoInDTO.getBankBranch())) {
				CertNo = agentInfoInDTO.getBankBranch();
				agent.setBankBranch(CertNo);
			}else{
				CertNo = agentInfoInDTO.getLegalPersonId();
			}
			
			//对私实名认证 对公不做处理
		   String verify = agent.getRecieveAccountType() == 1 ? "1" : "0";
		   
		   agentMapper.insert(agent);
		
		PayUserAccounts payUserAccounts = PayUserAccounts.initialize(GroupId, UserId, CustomerName, CertNo, PayPwd,
					PwdAnswer, PwdQuest, Email, MobilePhone, null, OrgTranDateTime,verify);
			PayResult payResult = IPayAPI.individualUserAccounts(payUserAccounts);
			if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
				throw new ApplicationException(Rescode.FAIL,payResult.getMsgTxt());
			}
			String CardDesc = agentInfoInDTO.getRecieveBank();
			QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, agentInfoInDTO.getRecieveAccountNo());
			PayCardCodeResult  payCardCode=IPayAPI.queryCardCode(queryCardCode);
			String accountType = "01";//表示借记卡
			if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
				if(payCardCode.getResult().get("CardType").contains("贷")){
					accountType = "00";//表示贷记记卡
				}
			}
			//22表示对私
			PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
					OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
					Integer.valueOf(verify),priOrpub);
			PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
			if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
				throw new ApplicationException(Rescode.FAIL,bindResult.getMsgTxt());
			}
			//设置费率
			Agent topAgent=agentMapper.selectMerchantCode(agent.getMerchantCode().substring(0,5));
			AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(topAgent.getId());
			//分润设置为平台设置 且为 2，3级代理商 需要设置好分润值
			if(agentRate!=null){
				Date date=new Date();
				if(agent.getAgentLevel().intValue()==2){
					agent.setPreprofitRate(agentRate.getSecondPurchaseRate());
					agent.setProfitRate(agentRate.getSecondFeeRate());
				}else if(agent.getAgentLevel().intValue()==3){
					agent.setPreprofitRate(agentRate.getThirdPurchaseRate());
					agent.setProfitRate(agentRate.getThirdFeeRate());
				}
				agent.setProfitUpdateTime(date);
				agent.setPreprofitValidTime(date);	
				agent.setPreprofitUpdateTime(date);
				agent.setProfitValidTime(date);
				userbase.setStatus(UserStatus.Normal.getType());
				agent.setAgentStatus((byte)AgentStatus.Normal.getType());
			}else{
				userbase.setStatus(UserStatus.Stop.getType());
				agent.setAgentStatus((byte)AgentStatus.Stop.getType());
			}


			//生成代理商二维码和链接

			String recommendLink=url+"/EBosMerchant/netIn/index?groupId="+agentInfoInDTO.getGroupId()+"&agentId="+agent.getId();
			agent.setRecommendLink(recommendLink);
			String recommendUrl=url+"/EBosMerchant/netIn/index?groupId="+agentInfoInDTO.getGroupId()+"&agentId="+agent.getId();
			agent.setRecommendUrl(recommendUrl);


			userbaseMapper.updateByPrimaryKey(userbase);
			agentMapper.updateByPrimaryKey(agent);
		    //调用发送邮件，和调用短信
			try {
				templateMailSendService.sendAgentCreateSms(group.getId() ,agentInfoInDTO.getPrincipalMobile(), agentInfoInDTO.getUsername(), agentInfoInDTO.getPassword());
				String content="您开通的代理商用户名为:"+agentInfoInDTO.getUsername()+"\n"+"密码为:"+agentInfoInDTO.getPassword()+"\n"+"商博士后台地址:"+url+"/EBosMerchant";
				templateMailSendService.sendMail("商户开通提醒", content, agentInfoInDTO.getUsername());
			} catch (Exception e) {
				e.printStackTrace();
			}
		return true;
	}

	@Override
	public Boolean updateAgentInfo(AgentInfoInDTO agentInfoInDTO) throws ApplicationException {
		Group group = groupMapper.selectByPrimaryKey(agentInfoInDTO.getGroupId());
		String GroupId = group.getPayGroupCode();
//		String CustomerName = agentInfoInDTO.getLegalPersonName();

		String CustomerName=agentInfoInDTO.getRecieveName();
	
		String MobilePhone = agentInfoInDTO.getPrincipalMobile();
		String OrgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		Agent agent = agentMapper.selectByPrimaryKey(agentInfoInDTO.getId());
//		agent.setLegalPersonName(CustomerName);
		agent.setRecieveName(CustomerName);
		agent.setPrincipalMobile(MobilePhone);
		String Email = agentInfoInDTO.getUsername();
		
		String PayPwd = agent.getPayPassword();
		String SysTraceNum = UtilFun.createRandomNum(10);
		String OrgOrderNum =UtilFun.createOrderNum();
		String CardNum = agentInfoInDTO.getRecieveAccountNo();//卡号
		agent.setRecieveAccountNo(CardNum);
		String issuerId = agentInfoInDTO.getRecieveBank();
		agent.setRecieveBank(issuerId);
		
		//身份证
		String CertNo =null;
		String cardIntegral = "000000000000";
		if (StringUtils.isNotBlank(agentInfoInDTO.getBankBranch())) {
			CertNo = agentInfoInDTO.getBankBranch();
		}else{
			CertNo = agentInfoInDTO.getLegalPersonId();
		}
		agent.setRecieveAccountType(Byte.valueOf(""+agentInfoInDTO.getRecieveAccountType()));
		agent.setLegalPersonId(CertNo);
		agent.setBankBranch(agentInfoInDTO.getBankBranch());
		agent.setGmtModified(new Date());
		agent.setMemo(agentInfoInDTO.getMemo());
		agent.setAgentType(Byte.valueOf(""+agent.getAgentType()));
		agent.setPrincipal(agentInfoInDTO.getPrincipal());
		agent.setPrincipalMobile(agentInfoInDTO.getPrincipalMobile());
//		agent.setRecieveName(agentInfoInDTO.getRecieveName());
		agent.setLegalPersonName(agentInfoInDTO.getLegalPersonName());

		agent.setBankProvince(agentInfoInDTO.getBankProvince());
		agent.setBankCity(agentInfoInDTO.getBankCity());
		agent.setBankDistrict(agentInfoInDTO.getBankDistrict());

		agent.setLegalPersonIdurl(agentInfoInDTO.getLegalPersonIdurl());
		agent.setAddressCity(agentInfoInDTO.getAddressCity());
		agent.setManageAddress(agentInfoInDTO.getManageAddress());
		agent.setAddressDistrict(agentInfoInDTO.getAddressDistrict());
		agent.setAddressProvince(agentInfoInDTO.getAddressProvince());
		agent.setFinanceContact(agentInfoInDTO.getFinanceContact());
		agent.setFinancePhone(agentInfoInDTO.getFinancePhone());
		
		agent.setSort(agentInfoInDTO.getSort());	
		agentMapper.updateByPrimaryKeySelective(agent);
		String CardDesc = BizEnum.WithdrawBankList.fromType(agentInfoInDTO.getRecieveBank()).getName();
		
		QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, agentInfoInDTO.getRecieveAccountNo());
		PayCardCodeResult  payCardCode=IPayAPI.queryCardCode(queryCardCode);
		String accountType = "01";//表示借记卡
		if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
			if("2".equals(payCardCode.getResult().get("card_type_int"))){
				accountType = "00";//表示贷记记卡
			}
		}
		String priOrpub = agent.getRecieveAccountType() == 1 ? "22" : "11";
		PayBindBankCard bindbank = PayBindBankCard.initialize(agent.getPacketNum(), PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
				OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
				0,priOrpub);
		PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
		if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL,bindResult.getRespCode() + "#" + bindResult.getMsgTxt());
		}
		PayUpdateData payUserAccounts = PayUpdateData.initialize(GroupId, agent.getPacketNum(), CustomerName, MobilePhone, CertNo,
				OrgTranDateTime, Email, null, "01","0");
		PayResult payResult = IPayAPI.updateAccountData(payUserAccounts);
		if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL,payResult.getRespCode() + "#" + payResult.getMsgTxt());
		}
		return true;
	}

	@Override
	public BaseOutDTO finishStopAgent(Long id) throws ApplicationException{
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		Agent agentTmp=agentMapper.selectByPrimaryKey(id);
		Userbase userbase=userbaseMapper.selectByPrimaryKey(agentTmp.getUserId());
		Byte agentStatus=agentTmp.getAgentStatus();
		if(agentStatus.toString().equals(AgentStatus.Normal.getType()+"")){ 
			agentTmp.setAgentStatus(Byte.valueOf(AgentStatus.Stop.getType()+""));
			userbase.setStatus(UserStatus.Stop.getType());
			baseOutDTO.setErrorCode(Rescode.SUCCESS, "停用");
		}else if(agentStatus.toString().equals(AgentStatus.Stop.getType()+"")){ 
			//判断 当前代理商 是否需要设置 分润
			GroupConfig groupConfig=groupConfigMapper.getSystemParamsByGroupId(agentTmp.getGroupId());
			if(groupConfig.getAgentMode().intValue()==1){
				//固定3级		
					if(agentTmp.getProfitRate()==null){
						AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(agentTmp.getId());
						 
						if(agentRate==null){
							  baseOutDTO.setErrorCode(Rescode.FAIL, "请先设置分润");
							  return baseOutDTO;
						 }else{
							 if(agentTmp.getAgentLevel().intValue()==1){
								 agentTmp.setProfitRate(agentRate.getFirstFeeRate());
								 agentTmp.setPreprofitRate(agentRate.getFirstPurchaseRate());
								 
							 }else if(agentTmp.getAgentLevel().intValue()==2){
								 agentTmp.setProfitRate(agentRate.getSecondFeeRate());
								 agentTmp.setPreprofitRate(agentRate.getSecondPurchaseRate());
								
							 }else{
								 agentTmp.setProfitRate(agentRate.getThirdFeeRate());
								 agentTmp.setPreprofitRate(agentRate.getThirdPurchaseRate());
								
							 }
							 agentTmp.setPreprofitValidTime(new Date());
							 agentTmp.setProfitValidTime(new Date());						 
							 agentTmp.setProfitUpdateTime(new Date());								
							 agentTmp.setPreprofitUpdateTime(new Date());
						 }
					}
				 
				
			}
			agentTmp.setAgentStatus(Byte.valueOf(AgentStatus.Normal.getType()+""));
			userbase.setStatus(UserStatus.Normal.getType());
			baseOutDTO.setErrorCode(Rescode.SUCCESS, "启用");
		}
		agentMapper.updateByPrimaryKey(agentTmp);
		userbaseMapper.updateByPrimaryKey(userbase);
		return baseOutDTO;
	}

	@Override
	public void updateAuditAgent(AgentApproveDTO agentInDTO) throws ApplicationException{
		Agent agentTmp=agentMapper.selectByPrimaryKey(agentInDTO.getId());
		Userbase userbase=userbaseMapper.selectByPrimaryKey(agentTmp.getUserId());
		if(agentInDTO.getAgentStatus().equals(AgentStatus.Normal.getType()+"")){ 
			String CardNum = agentTmp.getRecieveAccountNo();// legal_person_id
			String issuerId = agentTmp.getRecieveBank();
			String CustomerName = agentTmp.getRecieveName();
			String MobilePhone = agentTmp.getPrincipalMobile();
			String CertNo = agentTmp.getLegalPersonId();
			if(Tools.isEmpty(CardNum)||Tools.isEmpty(issuerId)||Tools.isEmpty(CustomerName)){
				throw new ApplicationException(Rescode.FAIL,"开户信息未填写完整,请修改资料后审核");
			}
			Group group = groupMapper.selectByPrimaryKey(agentTmp.getGroupId());
			String GroupId = group.getPayGroupCode();
			String UserId = GroupId + UtilFun.formatNumber(agentTmp.getUserId(), 10);
			agentTmp.setAgentStatus(Byte.valueOf(agentInDTO.getAgentStatus()+""));
			agentTmp.setPacketStatus(true);
			agentTmp.setPacketNum(UserId);
			agentTmp.setPrePurchaseMoney(0);
			agentMapper.updateByPrimaryKey(agentTmp);
			userbase.setStatus(UserStatus.Normal.getType());
			userbaseMapper.updateByPrimaryKey(userbase);
				//审核通过 开户
				String priOrpub = agentTmp.getRecieveAccountType() == 1 ? "22" : "11";
				String PayPwd="888888";
				String PwdAnswer = "000000";
				String PwdQuest = "000000";
				String Email = userbase.getUsername();
				String OrgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
				String SysTraceNum = UtilFun.createRandomNum(10);
				String OrgOrderNum =UtilFun.createOrderNum();
				String cardIntegral = "000000000000";
				String CardDesc = BizEnum.WithdrawBankList.fromType(issuerId).getName();
				QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, CardNum);
				PayCardCodeResult  payCardCode=IPayAPI.queryCardCode(queryCardCode);
				String accountType = "01";//表示借记卡
				if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
					if(payCardCode.getResult().get("CardType").contains("贷")){
						accountType = "00";//表示贷记记卡
					}
				}
				
				PayUserAccounts payUserAccounts = PayUserAccounts.initialize(GroupId, UserId, CustomerName, CertNo, PayPwd,
						PwdAnswer, PwdQuest, Email, MobilePhone, null, OrgTranDateTime,null);
				PayResult payResult = IPayAPI.individualUserAccounts(payUserAccounts);
				if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
					throw new ApplicationException(Rescode.FAIL,"支付平台开户失败:"+payResult.getMsgTxt());
				}
				//22表示对私
				PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
						OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
						1,priOrpub);
				PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
				if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
					throw new ApplicationException(Rescode.FAIL,"用户绑定银行卡失败:"+bindResult.getMsgTxt());
				}
		}else if(agentInDTO.getAgentStatus().equals(AgentStatus.AuditFailure.getType()+"")){
			agentTmp.setAgentStatus(Byte.valueOf(AgentStatus.AuditFailure.getType()+""));
			userbase.setStatus(UserStatus.Stop.getType());
			agentTmp.setMemoOne(agentInDTO.getMemo());
			agentMapper.updateByPrimaryKey(agentTmp);
			userbaseMapper.updateByPrimaryKey(userbase);
		}	
	}

	
	
	@Override
	public Boolean updateAgentVerifyInfo(AgentInfoInDTO agentInfoInDTO) throws ApplicationException {
		Group group = groupMapper.selectByPrimaryKey(agentInfoInDTO.getGroupId());
		
		String GroupId = group.getPayGroupCode();
		String CustomerName = agentInfoInDTO.getLegalPersonName();
		String CertNo = agentInfoInDTO.getLegalPersonId();
		String MobilePhone = agentInfoInDTO.getPrincipalMobile();
		String OrgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		Agent agent = agentMapper.selectByPrimaryKey(agentInfoInDTO.getId());
		Userbase userbase=userbaseMapper.selectByPrimaryKey(agent.getUserId());
		Boolean flag=agent.getPacketStatus();
		String UserId = GroupId + UtilFun.formatNumber(agent.getUserId(), 10);
		String Email = agentInfoInDTO.getUsername();
		String PwdAnswer = "000000";
		String PwdQuest = "000000";
		String PayPwd = agent.getPayPassword();
		
		try {
			PropertyCopyUtil.copyPropertiesNotNull(agentInfoInDTO, agent);
		} catch (Exception e) {
			throw new ApplicationException(Rescode.FAIL,"属性参数错误");
		}
		String SysTraceNum = UtilFun.createRandomNum(10);
		String OrgOrderNum =UtilFun.createOrderNum();
		String CardNum = agentInfoInDTO.getRecieveAccountNo();
		String cardIntegral = "000000000000";
//		if (StringUtils.isNotBlank(agentInfoInDTO.getBankBranch())) {
//			cardIntegral = agentInfoInDTO.getBankBranch();
//		}else{
//			agent.setBankBranch(cardIntegral);
//		}
		agent.setBankBranch(cardIntegral);
		String CardDesc = agentInfoInDTO.getRecieveBank();
		QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, agentInfoInDTO.getRecieveAccountNo());
		PayCardCodeResult  payCardCode=IPayAPI.queryCardCode(queryCardCode);
		String accountType = "01";//表示借记卡
		if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
			if("2".equals(payCardCode.getResult().get("card_type_int"))){
				accountType = "00";//表示贷记记卡
			}
		}
		agent.setGmtModified(new Date());
		agent.setPacketStatus(true);
		agentMapper.updateByPrimaryKey(agent);
		String priOrpub = agent.getRecieveAccountType() == 1 ? "22" : "11";
		//
		//设置费率
				Agent topAgent=agentMapper.selectMerchantCode(agent.getMerchantCode().substring(0,5));
				AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(topAgent.getId());
				if(agentRate!=null){
					Date date=new Date();
					if(agent.getAgentLevel().intValue()==1){
						agent.setPreprofitRate(agentRate.getFirstPurchaseRate());
						agent.setProfitRate(agentRate.getFirstFeeRate());
					}else if(agent.getAgentLevel().intValue()==2){
						agent.setPreprofitRate(agentRate.getSecondPurchaseRate());
						agent.setProfitRate(agentRate.getSecondFeeRate());
					}else if(agent.getAgentLevel().intValue()==3){
						agent.setPreprofitRate(agentRate.getThirdPurchaseRate());
						agent.setProfitRate(agentRate.getThirdFeeRate());
					}
					 					 
					agent.setProfitUpdateTime(new Date());								
					agent.setPreprofitUpdateTime(new Date());
					agent.setPreprofitValidTime(date);		
					agent.setProfitValidTime(new Date());
					userbase.setStatus(UserStatus.Normal.getType());
//					agent.setAgentStatus((byte)AgentStatus.Normal.getType());  agentStatus
					agent.setAgentStatus(agentInfoInDTO.getAgentStatus());
				}else{
					userbase.setStatus(UserStatus.Stop.getType());
					agent.setAgentStatus((byte)AgentStatus.Stop.getType());
				}	
		//开通钱包调用修改 未开通调用创建
				if(flag){
					String issuerId = agentInfoInDTO.getRecieveBank();
					PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
							OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
							0,priOrpub);
					PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
					if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
						throw new ApplicationException(Rescode.FAIL,bindResult.getRespCode() + "#" + bindResult.getMsgTxt());
					}
						PayUpdateData payUserAccounts = PayUpdateData.initialize(GroupId, UserId, CustomerName, MobilePhone, CertNo,
								OrgTranDateTime, Email, null, "01",null);//01表示用户正常  00表示用户禁用
						PayResult payResult = IPayAPI.updateAccountData(payUserAccounts);
						if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
							throw new ApplicationException(Rescode.FAIL,payResult.getRespCode() + "#" + payResult.getMsgTxt());
						}
				}else{
					    String issuerId = WithdrawBankList.fromType(agentInfoInDTO.getRecieveBank()).getName();
					    PayUserAccounts payUserAccounts = PayUserAccounts.initialize(GroupId, UserId, CustomerName, CertNo, PayPwd,
								PwdAnswer, PwdQuest, Email, MobilePhone, null, OrgTranDateTime,null);
						PayResult payResult = IPayAPI.individualUserAccounts(payUserAccounts);
						if (PayResult.SUCCESS.equals(payResult.getRespCode())||PayResult.USER_EXSIT.equals(payResult.getRespCode())) {
							agent.setPacketStatus(true);
							agent.setPacketNum(UserId);
						} else {
							throw new ApplicationException(Rescode.FAIL,"支付平台开户失败");
						}
						PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
								OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
								0,priOrpub);
						PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
						if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
							throw new ApplicationException(Rescode.FAIL,"代理商绑定银行卡失败");
						}						
				}
				agentMapper.updateByPrimaryKey(agent);
		return true;
	}
	
	
	@Override
	public AgentMoreInfoOutDTO findAgentInfoById(Long id) throws ApplicationException {
		AgentMoreInfoOutDTO agentInfoOutDTO = new AgentMoreInfoOutDTO();
		Agent agent=new Agent();
		agent.setId(id);
		AgentInfoOutDTO agentInfoDTO =agentMapper.findAgentbaseInfo(agent);
		if(agentInfoDTO.getRecommendLink()!=null){
			agentInfoDTO.setRecommendUrl(agentInfoDTO.getRecommendLink().replaceAll("&","%26"));
		}
		try {
			PropertyCopyUtil.copyPPropertiesNotNull(agentInfoDTO, agentInfoOutDTO);
		} catch (Exception e) {
			throw new ApplicationException(Rescode.FAIL,"对象复制异常");
		}
		GroupConfig groupConfig = groupConfigMapper.getSystemParamsByGroupId(agentInfoDTO.getGroupId());
		if(groupConfig==null){
			throw new ApplicationException(Rescode.FAIL,"暂未设置分润类型");
		}
		if(groupConfig.getAgentMode()==null){
			throw new ApplicationException(Rescode.FAIL,"代理商模式为空或未设置");
		}
		agentInfoOutDTO.setGroupAgentMode(Integer.valueOf(groupConfig.getAgentMode()));
		Group group = groupMapper.selectByPrimaryKey(agentInfoDTO.getGroupId());
		String GroupId = group.getPayGroupCode();
		String UserId=agentInfoDTO.getPacketNum();
		
		
		Wallet wallet=walletService.selectwallet(UserId, GroupId, agentInfoDTO.getUserId());
		
		
		Integer balance=wallet.getCanBalance()+wallet.getNocanBalance();

		Integer freezeBalance=wallet.getCanFreezeBalance();//+wallet.getCanFreezeBalance();//+wallet.getNocanBalance()
		Integer lockBalance = wallet.getCanBalanceLocked();
		agentInfoOutDTO.setBalance(balance);
		agentInfoOutDTO.setLockBalance(lockBalance);
		agentInfoOutDTO.setFreezeBalance(freezeBalance);
		return agentInfoOutDTO;
	}

	@Override
	public AgentFinanceInfoOut findAgentFinanceInfo(Long agentId) throws ApplicationException {
		AgentFinanceInfoOut agentFinanceInfoOut = new AgentFinanceInfoOut();
		Agent agent=agentMapper.selectByPrimaryKey(agentId);
		if(agent==null){
			throw new ApplicationException(Rescode.FAIL,"代理商不存在");
		}
		Group group = groupMapper.selectByPrimaryKey(agent.getGroupId());
		String GroupId = group.getPayGroupCode();
		String UserId=agent.getPacketNum();
		Wallet wallet=walletService.selectwallet(UserId, GroupId, agent.getUserId());
		Integer balance=wallet.getCanBalance()+wallet.getNocanBalance();
		Integer lockBalance=wallet.getCanBalanceLocked()+wallet.getNocanBalance()+wallet.getCanFreezeBalance();
		agentFinanceInfoOut.setAgentId(agentId);
		agentFinanceInfoOut.setBalance(balance);
		agentFinanceInfoOut.setLockBalance(lockBalance);
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("agentId",agentId);
		param.put("groupId",agent.getGroupId());
		StatisAgent profit=statisAgentMapper.selectStatisAgentByAgentId(param);
		if (profit!=null) {
			agentFinanceInfoOut.setTotalProfit(profit.getIncomeSumAmount());
			agentFinanceInfoOut.setAgentName(profit.getMerchantName());
		}
		return agentFinanceInfoOut;
	}

	@Override
	public AgentListOutDTO listGroupAgent(AgentInDTO agentInDTO) { 
		AgentListOutDTO agentListOutDTO = new AgentListOutDTO();
		//如果是代理商 只查询自己线下发展的代理商 且不能包含3级代理商 只能包含已经审核可以的
		 if(CommonEnum.UserType.Agents.getType()==agentInDTO.getUserType()){
			   Agent agent=agentMapper.selectByPrimaryKey(agentInDTO.getId());
		       agentInDTO.setAgentCode(agent.getMerchantCode());
		  }
		List<AgentInfoOutDTO> agentInfoOutDTOList = agentMapper.listGroupAgent(agentInDTO);
		agentListOutDTO.setAgentOutDTOList(agentInfoOutDTOList);
		agentListOutDTO.setErrorCode(Rescode.SUCCESS);
		return agentListOutDTO;
	}

	@Override
	public List<Map<String, Object>> listGroupAgent2(Long groupId) {
		List<Map<String, Object>> result = agentMapper.listAgentByGroupId(groupId);
		return result;
	}

	/**
	 * 前端注册代理商
	 */
	@Override
	public Boolean addAgentInfoVerify(AgentInfoInDTO agentInfoInDTO) throws ApplicationException {
		Agent parentAgent = agentMapper.selectByPrimaryKey(agentInfoInDTO.getParentId());
		if (parentAgent == null) {
			throw new ApplicationException(Rescode.FAIL,"上级代理商不存在");
		}
		agentInfoInDTO.setPrincipalMobile(Tools.getPhoneNum(agentInfoInDTO.getPrincipalMobile())); 
		// 生成UserBase
		String PayPwd = agentInfoInDTO.getPassword();
		Userbase userbase = new Userbase();
		userbase.setGmtCreate(new Date());
		userbase.setGmtModified(new Date());
		userbase.setUsername(agentInfoInDTO.getUsername());
		userbase.setPassword(new SimpleHash("SHA-1", agentInfoInDTO.getUsername(), PayPwd).toString());
		userbase.setUserType(UserType.Agents.getType());
		userbase.setStatus(UserStatus.Stop.getType());
		userbase.setGroupId(parentAgent.getGroupId());
		userbaseMapper.insertKey(userbase);
		Agent agent  = new Agent();
		try {
			PropertyCopyUtil.copyPropertiesNotNull(agentInfoInDTO, agent);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//默认地址为开户行
		agent.setAddressProvince(agentInfoInDTO.getBankProvince());
		agent.setAddressCity(agentInfoInDTO.getBankCity());
		agent.setAddressDistrict(agentInfoInDTO.getBankDistrict());
		agent.setUserId(userbase.getId());
		agent.setGmtCreate(new Date());
		agent.setCreator(agentInfoInDTO.getLastUpdator());
		agent.setPayPassword(PayPwd);
		agent.setGroupId(parentAgent.getGroupId());
		agent.setPacketStatus(false);
		agent.setRecieveAccountType(agentInfoInDTO.getRecieveAccountType());
		agent.setAgentLevel(parentAgent.getAgentLevel() + 1);
		String parentCode = parentAgent.getMerchantCode();
		//同一级+5
		String merchantCode = agentMapper.selectMaxMerchantCode(parentCode, parentCode.length() + 5);
		if (StringUtils.isBlank(merchantCode)) {
			//同级不存在
			agent.setMerchantCode(parentCode+"00001");
		} else {
			int merCode = Integer.parseInt(merchantCode.substring(merchantCode.length() - 5));
			String merchantCode_ = String.format("%05d", merCode+1);
			
			agent.setMerchantCode(parentCode + merchantCode_);
		}
		String cardIntegral = "000000000000";
		agent.setBankBranch(cardIntegral);
		agent.setPacketStatus(false);
		agent.setAgentStatus(Byte.valueOf(AgentStatus.WaitingForAudit.getType()+""));
		agent.setSource(BizEnum.AgentSource.External.getType());
		try {
			agent.setSort(0);
			agent.setPrePurchaseStatus(0);
			agentMapper.insert(agent);
		} catch (Exception e) {
			throw new ApplicationException(Rescode.FAIL,"代理商保存出现异常");
		}
		//调用发送邮件，和调用短信
		return true;
	}


	@Override
	public AgentRateOutDTO findAgentInfo(Long id) throws ApplicationException {
		// 取值代理商顶级编号 
		Long agentId = null; 
		Agent agent=agentMapper.selectByPrimaryKey(id);
		if(agent.getMerchantCode().length()==5){
			agentId=agent.getId();
		}else{
			String merchantCode=agent.getMerchantCode().substring(0,5);
			Agent agentchantCode=agentMapper.selectMerchantCode(merchantCode);
			agentId=agentchantCode.getId();
		}
		AgentRateOutDTO agentRateOutDTO=new AgentRateOutDTO();
		AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(agentId);
		if(agentRate!=null){
			try {
				PropertyCopyUtil.copyPropertiesNotNull(agentRate, agentRateOutDTO);
			} catch (Exception e) {
				throw new ApplicationException(Rescode.FAIL,"对象复制异常");
			}
		}
		agentRateOutDTO.setAgentLevel(agent.getAgentLevel());
		agentRateOutDTO.setErrorCode(Rescode.SUCCESS, "查询成功");
		return agentRateOutDTO;
	}


	@Override
	public Boolean saveSubSet(AgentRateInDTO agentRateInDTO) throws ApplicationException {
		 Agent  agent = agentMapper.selectByPrimaryKey(agentRateInDTO.getAgentId());
		if (agent == null) {
			throw new ApplicationException(Rescode.FAIL,"代理商不存在");
		}
		
		//模式为平台设置 需要同步更新该代理商下所有分润费率
		  if(agentRateInDTO.getFeeType().intValue()==0){
			  List<Agent> agentList = agentMapper.listMerchanCodeAgent(agent.getMerchantCode());
			  for (Agent agentMap : agentList) {
				  siteAgentRate(agentRateInDTO,agentMap); 
				 }	
			  /**
			   * 查询这个一级代理商的所有车门店
			   */
			
			  List<YsShopCar>ysShopCards=  ysShopCarMapper.selectByTopAgent(agent.getMerchantCode());
			 Date date= new Date();
			  for(YsShopCar ysShopCar:ysShopCards){
		    	 if(ysShopCar.getProfitRate()==null){
		    		 ysShopCar.setProfitRate(agentRateInDTO.getThirdFeeRate());  				    	
		    		 ysShopCar.setProfitUpdateTime(date);
		    		 ysShopCar.setProfitValidTime(date);
				    	
		    	 }else{
		    		 ysShopCar.setNewProfitRate(agentRateInDTO.getThirdFeeRate());  				    	
		    		 ysShopCar.setProfitUpdateTime(date);
		    	 }
                 if(ysShopCar.getPreprofitRate()==null){
                	  				    	
		    		 ysShopCar.setPreprofitRate(agentRateInDTO.getThirdPurchaseRate());				
		    		 ysShopCar.setPreprofitUpdateTime(date);
		    		 ysShopCar.setPreprofitValidTime(date);
		    	 }else{
		    		 ysShopCar.setNewPreprofitRate(agentRateInDTO.getThirdPurchaseRate());  				    	
		    		 ysShopCar.setProfitUpdateTime(date);
		    	 }
                 ysShopCarMapper.updateByPrimaryKey(ysShopCar);
		      }
		  }else{
			  siteAgentRate(agentRateInDTO,agent);  
		  }
		AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(agent.getId()); 
		//未设置消费分润和预采购分润
		if(agentRate==null){
			try {
				AgentRate agentRateCopy=new AgentRate();
				PropertyCopyUtil.copyPropertiesNotNull(agentRateInDTO, agentRateCopy);
				agentRateCopy.setGmtCreate(new Date()); 
				agentRateCopy.setAgentId(agent.getId());
				agentRateMapper.insert(agentRateCopy);
				return true; 
			} catch (Exception e) {
				e.printStackTrace();
				throw new ApplicationException(Rescode.FAIL,"对象拷贝异常");
		    }		
		}else{
			try {
				PropertyCopyUtil.copyPropertiesNotNull(agentRateInDTO, agentRate);
				 agentRateMapper.updateByPrimaryKey(agentRate);
			  } catch (Exception e) {
				  e.printStackTrace();
				throw new ApplicationException(Rescode.FAIL,"对象拷贝异常");
			  }
			  return true; 	 
		 }
	}

	/**
	 * 平台设置模式--批量更新同一大商户代理商费率信息
	 * @param agentRateInDTO
	 * @param agentMap
	 */
	 public void siteAgentRate(AgentRateInDTO agentRateInDTO,Agent agentMap){
		     Date date=new Date();
			   if(agentMap.getMerchantCode().length()==5){
				   // 分润比例未设置 直接修改分润比较 分润比例已设置 填写至 最新修改的分润费率 等待批量任务更新
				    if(agentMap.getProfitRate()==null||agentMap.getPreprofitRate()==null){
				    	agentMap.setProfitRate(agentRateInDTO.getFirstFeeRate());  			    	
				    	agentMap.setPreprofitRate(agentRateInDTO.getFirstPurchaseRate());				    
				    	agentMap.setProfitValidTime(date);
				    	agentMap.setProfitUpdateTime(date);
				    	agentMap.setPreprofitUpdateTime(date);
				    	agentMap.setPreprofitValidTime(date);
					}else{
						agentMap.setNewProfitRate(agentRateInDTO.getFirstFeeRate()); 
						agentMap.setProfitUpdateTime(date); 
						agentMap.setNewPreprofitRate(agentRateInDTO.getFirstPurchaseRate());
						agentMap.setPreprofitUpdateTime(date);
					}			   
			     }else if(agentMap.getMerchantCode().length()==10){
					   if(agentMap.getProfitRate()==null||agentMap.getPreprofitRate()==null){
						   agentMap.setProfitRate(agentRateInDTO.getSecondFeeRate());  
					    	agentMap.setPreprofitRate(agentRateInDTO.getSecondPurchaseRate());
					    	agentMap.setProfitValidTime(date);
					    	agentMap.setProfitUpdateTime(date);
					    	agentMap.setPreprofitUpdateTime(date);
					    	agentMap.setPreprofitValidTime(date);
						}else{
							agentMap.setNewProfitRate(agentRateInDTO.getSecondFeeRate()); 
							agentMap.setProfitUpdateTime(date); 
							agentMap.setNewPreprofitRate(agentRateInDTO.getSecondPurchaseRate());
							agentMap.setPreprofitUpdateTime(date);
						}
					   
				   }
			     else if(agentMap.getMerchantCode().length()==15){
					   if(agentMap.getProfitRate()==null||agentMap.getPreprofitRate()==null){

						    agentMap.setProfitRate(agentRateInDTO.getThirdFeeRate());  				    	
					    	agentMap.setPreprofitRate(agentRateInDTO.getThirdPurchaseRate());				
					    	agentMap.setProfitValidTime(date);
					    	agentMap.setProfitUpdateTime(date);
					    	agentMap.setPreprofitUpdateTime(date);
					    	agentMap.setPreprofitValidTime(date);
						}else{
							agentMap.setNewProfitRate(agentRateInDTO.getThirdFeeRate()); 
							agentMap.setProfitUpdateTime(date); 
							agentMap.setNewPreprofitRate(agentRateInDTO.getThirdPurchaseRate());
							agentMap.setPreprofitUpdateTime(date);
					  }
					 
			     }
				    agentMapper.updateByPrimaryKeySelective(agentMap);
	}
	
	 @Override
	 public Boolean doUpdateAgentProfit(SingleAgentRateInDTO singleAgentRateInDTO) throws ApplicationException {
		 Date date=new Date();
		 Agent agentMap=agentMapper.selectByPrimaryKey(singleAgentRateInDTO.getId());
		  if(agentMap.getProfitRate()==null||agentMap.getPreprofitRate()==null){
		    	agentMap.setProfitRate(singleAgentRateInDTO.getProfitRate());  			    	
		    	agentMap.setPreprofitRate(singleAgentRateInDTO.getPreProfitRate());				    
		    	agentMap.setProfitValidTime(date);
		    	agentMap.setProfitUpdateTime(date);
		    	agentMap.setPreprofitUpdateTime(date);
		    	agentMap.setPreprofitValidTime(date);
			}else{
				agentMap.setNewProfitRate(singleAgentRateInDTO.getProfitRate()); 
				agentMap.setProfitUpdateTime(date); 
				agentMap.setNewPreprofitRate(singleAgentRateInDTO.getPreProfitRate());
				agentMap.setPreprofitUpdateTime(date);
			}
		  return agentMapper.updateByPrimaryKey(agentMap)>0;
	 }
	

	@Override
	public boolean doPrePurAgentUpdate(PrePurAgentInDTO prePurAgentInDTO) throws ApplicationException {
		 Agent agent=	agentMapper.selectByPrimaryKey(prePurAgentInDTO.getAgentId());
		if(prePurAgentInDTO.getPrePurchaseStatus().intValue()==1){
			//表示启用
			if(prePurAgentInDTO.getAmount()>0){
				//对他的预授权的金额进行调整
				//授权金额 这里单位为元 所以需要乘以100
				prePurAgentInDTO.setAmount(prePurAgentInDTO.getAmount()*100);
				//操作之前验证数据安全性是否完整
				if(SysUtils.Object2int(agent.getPrePurchaseBalance())!=0){
					
					String descBalance=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
					if(!descBalance.equalsIgnoreCase(agent.getPrePurchaseBalanceDes())){
						throw new ApplicationException("代理商的余额信息不正常，请联系客服");
					}
				}
				
               if(SysUtils.Object2int(agent.getPrePurchaseMoney())!=0){
            	   String descMoney=SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
					if(!descMoney.equalsIgnoreCase(agent.getPrePurchaseMoneyDes())){
						throw new ApplicationException("代理商的预授权额度信息不正常，请联系客服");
					}
       			
				}
               //
               PrePurchaseMoneyChange prePurchaseMoneyChange=new PrePurchaseMoneyChange();
               prePurchaseMoneyChange.setAgentId(agent.getId());
               
               prePurchaseMoneyChange.setAttachFile(prePurAgentInDTO.getFileUrl());
               prePurchaseMoneyChange.setAmount(prePurAgentInDTO.getAmount()*1L);
               prePurchaseMoneyChange.setChangeType(prePurAgentInDTO.getChangeType());
               prePurchaseMoneyChange.setGmtCreate(new Date());
               prePurchaseMoneyChange.setGmtModified(new Date());
               prePurchaseMoneyChange.setGroupId(prePurAgentInDTO.getGroupId());
               String balanceStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseBalance())/100, 2);
               String moneyStr=SysUtils.formatNumber(SysUtils.Object2int(agent.getPrePurchaseMoney())/100, 2);
               prePurchaseMoneyChange.setInfoDesc(prePurAgentInDTO.getInfoDesc()+";渠道调整前余额为"+balanceStr+",额度为"+moneyStr
            		   +",调整金额为" +SysUtils.formatNumber(prePurAgentInDTO.getAmount()/100,2));
               prePurchaseMoneyChange.setOperateUser(prePurAgentInDTO.getLastUpdator());
               prePurchaseMoneyChange.setOperateUserId(prePurAgentInDTO.getLastUserId());
               prePurchaseMoneyChange.setType(1);//表示渠道调整
               if(prePurAgentInDTO.getChangeType().intValue()==1){
            	   //表示+余额
            	 int balance = SysUtils.Object2int(agent.getPrePurchaseBalance())+prePurAgentInDTO.getAmount();
            	 agent.setPrePurchaseBalance(balance);  
            	 String descMoney=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
            	 agent.setPrePurchaseBalanceDes(descMoney);
            	 
            	 int total = SysUtils.Object2int(agent.getPrePurchaseMoney())+prePurAgentInDTO.getAmount();
            	 agent.setPrePurchaseMoney(total);
            	 String descTotal=SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
            	 agent.setPrePurchaseMoneyDes(descTotal);
               }else{
            	   //表示减余额
            	   if(agent.getPrePurchaseBalance()<prePurAgentInDTO.getAmount()){
            		   throw new ApplicationException("代理商余额调整失败，余额不足");
            	   }
            	   
            	  int balance = SysUtils.Object2int(agent.getPrePurchaseBalance())-prePurAgentInDTO.getAmount();
              	 agent.setPrePurchaseBalance(balance);  
              	 String descMoney=SysUtils.string2MD5(agent.getPrePurchaseBalance() + SysUtils.formatString(agent.getId(), 7));
              	 agent.setPrePurchaseBalanceDes(descMoney);
              	 
              	 int total = SysUtils.Object2int(agent.getPrePurchaseMoney())-prePurAgentInDTO.getAmount();
              	 agent.setPrePurchaseMoney(total);
              	 String descTotal=SysUtils.string2MD5(agent.getPrePurchaseMoney() + SysUtils.formatString(agent.getId(), 7));
              	 agent.setPrePurchaseMoneyDes(descTotal);
               }
               
               prePurchaseMoneyChangeMapper.insert(prePurchaseMoneyChange);
			}
			//暂停他的预授权状态，不能新建预售活动 ，修改他的状态信息 并且站内信消息通知
			  agent.setPrePurchaseStatus(1);
			  agent.setLastUpdator(prePurAgentInDTO.getLastUpdator());
			  agent.setGmtModified(new Date());
			  agentMapper.updateByPrimaryKey(agent);
		}else{
		 
			//暂停他的预授权状态，不能新建预售活动 ，修改他的状态信息 并且站内信消息通知
		  agent.setPrePurchaseStatus(0);
		  agent.setLastUpdator(prePurAgentInDTO.getLastUpdator());
		  agent.setGmtModified(new Date());
		  agentMapper.updateByPrimaryKey(agent);
		  //发送站内信

	        //插入系统消息表
	        SysMessageBase sysMessageBase = new SysMessageBase();
	        sysMessageBase.setGmtCreate(new Date());
	        sysMessageBase.setGmtModified(new Date());
	        sysMessageBase.setGroupId(prePurAgentInDTO.getGroupId());
	        sysMessageBase.setLevel((byte)0);	  
	        sysMessageBase.setSendFromName(prePurAgentInDTO.getLastUpdator());
	        sysMessageBase.setMessageType((byte) BizEnum.MessageType.AgentMessage.getType());
	        sysMessageBase.setTitle("预采购授权暂停通知");
	        StringBuffer buffer=new StringBuffer();
	        buffer.append(prePurAgentInDTO.getLastUpdator()).append(DateUtil.fomatDate(new Date(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")))
	        .append("停止您的预采购业务(不影响之前已经审核的预采购活动的进行)，原因如下：").append(prePurAgentInDTO.getInfoDesc()).append("如有疑问请联系客服");
	        sysMessageBase.setMemo(buffer.toString());
	        sysMessageBase.setSendFrom(prePurAgentInDTO.getLastUserId());
	        sysMessageBase.setSendStatus((byte) 0);  //发送失败
	        
	       
	        sysMessageBaseMapper.insert(sysMessageBase);
		    SysMessageInfo sysMessageInfo=new SysMessageInfo();
		    sysMessageInfo.setGmtCreate(new Date());
		    sysMessageInfo.setGmtModified(new Date()); 
		    sysMessageInfo.setReceviceUserId( agent.getUserId()); 
		    sysMessageInfo.setHasRead((byte)0); 
		    sysMessageInfo.setMessageId(sysMessageBase.getId());
		    sysMessageInfo.setIsDelete(null);
		    sysMessageInfoMapper.insert(sysMessageInfo);
	        

		}
		return true;
	}


	@Override
	public SubAgentSetInfoOutDTO findAgentSetInfo(Long agentId, Integer agentLevel) throws ApplicationException {
		SubAgentSetInfoOutDTO subAgentSetInfoOutDTO=new SubAgentSetInfoOutDTO();
		Agent agent =new Agent();
		agent.setId(agentId);
		//查询出当前代理商的信息
		AgentInfoOutDTO agentInfoOutDTO=agentMapper.findAgentbaseInfo(agent);
		subAgentSetInfoOutDTO.setId(agentId);
		subAgentSetInfoOutDTO.setAgentLevel(agentInfoOutDTO.getAgentLevel());
		subAgentSetInfoOutDTO.setAgentType(agentInfoOutDTO.getAgentType());
		subAgentSetInfoOutDTO.setMerchantCode(agentInfoOutDTO.getMerchantCode());
		subAgentSetInfoOutDTO.setMerchantName(agentInfoOutDTO.getMerchantName());
		subAgentSetInfoOutDTO.setNewPreprofitRate(agentInfoOutDTO.getNewPreprofitRate());
		subAgentSetInfoOutDTO.setNewProfitRate(agentInfoOutDTO.getNewProfitRate());
		subAgentSetInfoOutDTO.setPreprofitRate(agentInfoOutDTO.getPreprofitRate());
		subAgentSetInfoOutDTO.setProfitRate(agentInfoOutDTO.getPreprofitRate());
		subAgentSetInfoOutDTO.setProfitUpdateTime(agentInfoOutDTO.getProfitUpdateTime());
		subAgentSetInfoOutDTO.setPreprofitUpdateTime(agentInfoOutDTO.getPreprofitUpdateTime());
		subAgentSetInfoOutDTO.setPreprofitValidTime(agentInfoOutDTO.getPreprofitValidTime());
		subAgentSetInfoOutDTO.setProfitValidTime(agentInfoOutDTO.getProfitValidTime());
		
		String topMerchantCode=agentInfoOutDTO.getMerchantCode().substring(0,5);
		Agent topAgent= agentMapper.selectMerchantCode(topMerchantCode);		
		AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(topAgent.getId());
		subAgentSetInfoOutDTO.setFeeType(agentRate.getFeeType());
		return subAgentSetInfoOutDTO;
	}


	@Override
	public Boolean doAgentApprove(AgentInfoInDTO agentInfoInDTO) throws ApplicationException {
		Agent agentTmp=agentMapper.selectByPrimaryKey(agentInfoInDTO.getId());
		Userbase userbase=userbaseMapper.selectByPrimaryKey(agentTmp.getUserId());
		String CardNum = agentInfoInDTO.getRecieveAccountNo();// legal_person_id
		String issuerId = agentInfoInDTO.getRecieveBank();
		String CustomerName = agentInfoInDTO.getRecieveName();
		
		String CertNo = agentInfoInDTO.getLegalPersonId();
		
		//legalPersonName
		agentTmp.setLegalPersonId(agentInfoInDTO.getLegalPersonId());
		agentTmp.setLegalPersonName(agentInfoInDTO.getLegalPersonName());
		agentTmp.setRecieveName(agentInfoInDTO.getRecieveName());
		agentTmp.setLegalPersonIdurl(agentInfoInDTO.getLegalPersonIdurl());
		agentTmp.setRecieveAccountNo(agentInfoInDTO.getRecieveAccountNo());
		agentTmp.setRecieveBank(agentInfoInDTO.getRecieveBank());
		agentTmp.setFinanceContact(agentInfoInDTO.getFinanceContact());
		agentTmp.setFinancePhone(agentInfoInDTO.getFinancePhone());
		String MobilePhone = agentTmp.getPrincipalMobile();
		if(Tools.isEmpty(CardNum)||Tools.isEmpty(issuerId)||Tools.isEmpty(CustomerName)){
			throw new ApplicationException(Rescode.FAIL,"开户信息未填写完整,请修改资料后审核");
		}
		Group group = groupMapper.selectByPrimaryKey(agentTmp.getGroupId());
		String GroupId = group.getPayGroupCode();
		String UserId = GroupId + UtilFun.formatNumber(agentTmp.getUserId(), 10);
		
		//审核通过 开户
		String priOrpub = agentTmp.getRecieveAccountType() == 1 ? "22" : "11";
		String PayPwd=agentTmp.getPayPassword();
		String PwdAnswer = "000000";
		String PwdQuest = "000000";
		String Email = userbase.getUsername();
		String OrgTranDateTime = DateUtils.getDateTimeString("yyyyMMddHHmmss");
		String SysTraceNum = UtilFun.createRandomNum(10);
		String OrgOrderNum =UtilFun.createOrderNum();
		String cardIntegral = "000000000000";
		String CardDesc = BizEnum.WithdrawBankList.fromType(issuerId).getName();
		QueryCardCode queryCardCode=QueryCardCode.initialize(GroupId, CardNum);
		PayCardCodeResult  payCardCode=IPayAPI.queryCardCode(queryCardCode);
		String accountType = "01";//表示借记卡
		if(PayResult.SUCCESS.equals(payCardCode.getRespCode())){
			if(payCardCode.getResult().get("CardType").contains("贷")){
				accountType = "00";//表示贷记记卡
			}
		}
		
		PayUserAccounts payUserAccounts = PayUserAccounts.initialize(GroupId, UserId, CustomerName, CertNo, PayPwd,
				PwdAnswer, PwdQuest, Email, MobilePhone, null, OrgTranDateTime,null);
		PayResult payResult = IPayAPI.individualUserAccounts(payUserAccounts);
		if (!PayResult.SUCCESS.equals(payResult.getRespCode())&&!PayResult.USER_EXSIT.equals(payResult.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL,"支付平台开户失败:"+payResult.getMsgTxt());
		}
		//进行绑卡更新
		//22表示对私
		PayBindBankCard bindbank = PayBindBankCard.initialize(UserId, PayPwd, SysTraceNum, GroupId, OrgTranDateTime,
				OrgOrderNum, CardNum, CustomerName, accountType, MobilePhone, CertNo, issuerId, cardIntegral, CardDesc,
				1,priOrpub);
		PayResult bindResult = IPayAPI.userBindBankCard(bindbank);
		if (!PayResult.SUCCESS.equals(bindResult.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL,"用户绑定银行卡失败:"+bindResult.getMsgTxt());
		}
		
		agentTmp.setPacketStatus(true);
		agentTmp.setPacketNum(UserId);
		agentTmp.setPrePurchaseMoney(0);
		//设置费率
		Agent topAgent=agentMapper.selectMerchantCode(agentTmp.getMerchantCode().substring(0,5));
		AgentRate agentRate=agentRateMapper.selectByPrimaryAgentId(topAgent.getId());
		if(agentRate!=null){
			Date date=new Date();
			if(agentTmp.getAgentLevel().intValue()==1){
				agentTmp.setPreprofitRate(agentRate.getFirstPurchaseRate());
				agentTmp.setProfitRate(agentRate.getFirstFeeRate());
			}else if(agentTmp.getAgentLevel().intValue()==2){
				agentTmp.setPreprofitRate(agentRate.getSecondPurchaseRate());
				agentTmp.setProfitRate(agentRate.getSecondFeeRate());
			}else if(agentTmp.getAgentLevel().intValue()==3){
				agentTmp.setPreprofitRate(agentRate.getThirdPurchaseRate());
				agentTmp.setProfitRate(agentRate.getThirdFeeRate());
			}
			 						 
			agentTmp.setProfitUpdateTime(new Date());								
			 agentTmp.setPreprofitUpdateTime(new Date());
			agentTmp.setPreprofitValidTime(date);		
			agentTmp.setProfitValidTime(new Date());
			userbase.setStatus(UserStatus.Normal.getType());
			agentTmp.setAgentStatus((byte)AgentStatus.Normal.getType());
		}else{
			userbase.setStatus(UserStatus.Stop.getType());
			agentTmp.setAgentStatus((byte)AgentStatus.Stop.getType());
		}		
		agentMapper.updateByPrimaryKey(agentTmp);
		
		userbaseMapper.updateByPrimaryKey(userbase);
		//发送短信通知
		//调用发送邮件，和调用短信
		try {
			templateMailSendService.sendAgentCreateSms(group.getId() ,agentInfoInDTO.getPrincipalMobile(), agentInfoInDTO.getUsername(), agentInfoInDTO.getPassword());
			
			String content="您开通的代理商用户名为:"+agentInfoInDTO.getUsername()+"密码为"+agentInfoInDTO.getPassword();
			templateMailSendService.sendMail("商户开通提醒", content, agentInfoInDTO.getUsername());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;	
	}


	@Override
	public AgentListOutDTO getProvincelist() {
		AgentListOutDTO agentListOutDTO = new AgentListOutDTO();
		List<AgentInfoOutDTO> agentList=agentMapper.getAllAgentProvince();
		agentListOutDTO.setAgentOutDTOList(agentList);
		return agentListOutDTO;
	}

	//余额增加操作
	@Override
	public BaseOutDTO addBalance(BalanceInDTO balanceInDTO,String rootHomeUrl) throws ApplicationException {
     	//余额增加操作
		StringBuffer sb = new StringBuffer();
		//取得代理商的虚拟卡号
		Agent agent = agentMapper.selectByPrimaryKey(balanceInDTO.getId());
		Group group = groupMapper.selectByPrimaryKey(balanceInDTO.getGroupId());

		Integer tranAmt = Integer.valueOf(balanceInDTO.getTranAmt()) * 100;
		String OrgOrderNum = UtilFun.createOrderNum();
		//插入线下交易表
				TradeOffline tradeOffline = new TradeOffline();
				tradeOffline.setGmtCreate(new Date());
				tradeOffline.setGmtModified(new Date());
				tradeOffline.setGroupId(balanceInDTO.getGroupId());
				tradeOffline.setOrderId(OrgOrderNum);
				tradeOffline.setPayerId(group.getId());
				tradeOffline.setPayerName(group.getMerchantName());
				tradeOffline.setPayerType((byte) CommonEnum.UserType.BusinessManager.getType());
				tradeOffline.setReceiverId(agent.getId().toString());
				tradeOffline.setReceiverName(agent.getMerchantName());
				tradeOffline.setReceiverType((byte) CommonEnum.UserType.Agents.getType());
				tradeOffline.setOrderAmount(tranAmt);
				tradeOffline.setRealAmount(tranAmt);
				tradeOffline.setPayType((byte)BizEnum.PaymentType.Wallet.getType());
				tradeOffline.setTransactionType((byte) BizEnum.TransactionType.addAgentBalance.getType());// 交易类型
				tradeOffline.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
				tradeOffline.setTransactionStatus((byte)BizEnum.TransactionStatus.Success.getType());
				tradeOffline.setIsWallet(Boolean.TRUE);
				tradeOffline.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
				tradeOffline.setMemo("大商户修改余额");
				tradeOffline.setDetail("大商户修改余额");
				tradeOffline.setInNetCompany((byte)BizEnum.InNetCompany.fuqianla.getType());
				int result = tradeOfflineMapper.insertSelective(tradeOffline);
                if(result<=0){
                	throw new ApplicationException(Rescode.FAIL,sb.append("数据库操作失败。").append(")").toString());
                	
                }
		
		PayResult payResult=walletService.updateUserLockedAmount(agent.getPacketNum(), group.getPayGroupCode(), agent.getUserId(), tranAmt+"", "1", 0,OrgOrderNum);
		if(payResult==null){
			throw new ApplicationException(Rescode.FAIL,sb.append("余额变化失败。").append(")").toString());
		}
		BaseOutDTO baseOutDTO=new BaseOutDTO();
		baseOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
		return baseOutDTO;
	}

	@Override
	public MemberOutDTO queryAgentAmount(AgentInDTO agentInDTO) throws ApplicationException {
//		Member member = memberMapper.queryGroup(memberInDTO.getId());
		Agent agent = agentMapper.selectByPrimaryKey(agentInDTO.getId());
		Group group= groupMapper.selectPayCodeById(agentInDTO.getGroupId());

//		Wallet wallet=walletService.selectwallet(member.getVirtualCard(), member.getPayGroupCode(), agent.getUserId());
		Wallet wallet=walletService.selectwallet(agent.getPacketNum(), group.getPayGroupCode(), agent.getUserId());
		MemberOutDTO memberOutDTO = new MemberOutDTO();
		memberOutDTO.setCurBal(wallet.getCanBalance()+"");
		memberOutDTO.setCurBalB(wallet.getNocanBalance()+"");
		memberOutDTO.setLockBal((wallet.getCanBalanceLocked()+wallet.getCanFreezeBalance())+"");
		memberOutDTO.setLockBalB((wallet.getNocanBalanceLocked()+wallet.getNocanFreezeBalance())+"");
		memberOutDTO.setPhone(group.getPrincipalMobile());
		memberOutDTO.setVirtualCard(agent.getPacketNum());
		return memberOutDTO;
	}

    @Override
    public GroupOutDTO queryGroupInfoByGroupId(AgentInDTO agentInDTO) throws ApplicationException {

        return groupMapper.queryGroupInfoByGroupId(agentInDTO.getGroupId());
    }

    @Override
    public MemberOutDTO addAgentBalance(BalanceInDTO balanceInDTO, String root_home_url) throws ApplicationException {
        MemberOutDTO memberOutDTO = new MemberOutDTO();
        Integer tranAmt = Integer.valueOf(balanceInDTO.getTranAmt()) * 100;
        Agent agent = agentMapper.selectByPrimaryKey(balanceInDTO.getId());
        Group group=groupMapper.selectPayCodeById(balanceInDTO.getGroupId());
        String orgOrderNum = DateUtils.getDateTimeString("yyyyMMddHHmmss");
        Date date = new Date();
        TradeOffline trade = new TradeOffline();
        trade.setGmtCreate(date);
        trade.setGmtModified(date);
        trade.setGroupId(group.getId());
        trade.setOrderId(orgOrderNum);
        trade.setPayerId(group.getId());// 付款者id号
        trade.setPayerName(group.getMerchantName());// 付款者姓名
        trade.setPayerType((byte) CommonEnum.UserType.User.getType());
        trade.setPayType((byte) BizEnum.PaymentType.Wallet.getType());// 支付方式
        // 生成订单支付方式未知
        trade.setReceiverId(agent.getId().toString());// 接收者id
        trade.setReceiverName(agent.getMerchantName());// 接收者 此处以核销录入数据
        trade.setTransactionType((byte) BizEnum.TransactionType.addAgentBalance.getType());// 交易类型
        trade.setSubType((byte) BizEnum.PaymentScene.Online.getType());// 支付场景
        trade.setOrderAmount(tranAmt); // 订单金额
        trade.setDiscountAmount(0);// 折扣金额
        trade.setRealAmount(tranAmt);// 实付金额
        trade.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());// 交易状态
        trade.setIsWallet(false);
        trade.setGoodType(null);// 商品类型(线上用) ？
        trade.setMemo(Tools.notEmpty(balanceInDTO.getRemark())?balanceInDTO.getRemark():"大商户修改代理商余额");
        trade.setDetail(Tools.notEmpty(balanceInDTO.getRemark())?balanceInDTO.getRemark():"大商户修改代理商余额");
        trade.setMerchantNo(null);// 商户号(对账用)
        trade.setTerminalNo(null);// 商户终端号
        trade.setPayAccount("");// 支付卡号
        trade.setScanOrganization(null);// 扫码付入网机构
        trade.setCrcodeStr(null);
        trade.setOldOrderId(null);
        trade.setDividableAmount(0);// 可分润金额
        trade.setAttachStatus(BizEnum.ProfitCalculateStatus.NoDeal.getType());
        trade.setPayOrderid(orgOrderNum);
        trade.setPayBakOrderid(null);
        trade.setInNetCompany(null);// 入网机构
        tradeOfflineMapper.insertSelective(trade);
        PayResult flag=walletService.updateUserLockedAmount(agent.getPacketNum(), group.getPayGroupCode(), agent.getUserId(), tranAmt+"", balanceInDTO.getCanDraw(), 0,orgOrderNum);
        if (flag!=null) {
            // 增加余额成功
            memberOutDTO.setErrorCode(Rescode.SUCCESS, "处理成功");
            logger.info("--余额增加成功--");
//            // 云流消息发送
//            if (Tools.notEmpty(member.getThirdUserId())) {
//                try {
//                    wxApiWalletServiceService.updatefinishSendMessage(orgOrderNum, UserAuthApi.MC_BLANCE_CHANGE);
//                } catch (Exception e) {
//                    logger.info("--云流消息发送异常--");
//                }
//            }else if(Tools.notEmpty(member.getOpenid())){
//                //微信发送模板消息
//                try {
//                    templateMailSendService.sendTemplate(trade,  BizEnum.WebTemplateType.template13.getType(), trade.getPayerId(),
//                            trade.getGroupId(), BizEnum.PaymentType.WebChat.getType(),rootHomeUrl);
//                } catch (Exception e) {
//                    logger.info ("模板消息发送失败"+e);
//                }
//
//            }
            return memberOutDTO;
        } else {
            throw new ApplicationException(Rescode.FAIL, "余额变化失败");
        }

    }



	/**
	 * 重置支付密码
	 */
	@Override
	public Agent reSetPayPwd(MemberInDTO memberInDTO, String rootHomeUrl) throws Exception {
		Agent agent = agentMapper.reSetPayPwdById(memberInDTO.getId());
		String sysTraceNum = StringUtil.getRandNumberStr(12);// 交易流水号12位
		String groupId = agent.getPayGroupCode();
		String newPwd = "000000";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
		Date date = new Date();
		String str = simpleDateFormat.format(date);
		String orgTranDateTime = str;
		agent.setId(memberInDTO.getId());
		agent.setPayPassword(AES.AESEncode(Const.AceKey, "000000"));
		agent.setGmtModified(new Date());
		agentMapper.updateByPrimaryKeySelective(agent);
		FindbackPayPwd payUpdateRestPwd = FindbackPayPwd.initialize(agent.getPacketNum(), newPwd, groupId, sysTraceNum, orgTranDateTime, "000000", "000000");
		PayResult payResult = IPayAPI.findbackAccountPayPwd(payUpdateRestPwd);
		if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
			throw new Exception(payResult.getRespCode() + "#" + payResult.getMsgTxt());
		}
		try {
			templateMailSendService.sendMemberTemplate(agent.getId(), BizEnum.WebTemplateType.template14.getType(), rootHomeUrl, "支付");
		} catch (Exception e) {
			logger.info("模板消息发送失败" + e);
		}
		return agent;
	}

	@Override
	public GroupOutDTO getAgentNameById(Long agentId) throws Exception {
		GroupOutDTO groupOutDTO = new GroupOutDTO();
		Agent agent=agentMapper.selectByPrimaryKey(agentId);
		groupOutDTO.setMerchantName(agent.getMerchantName());
		return groupOutDTO;
	}

}
